package ca.etsmtl.log540.tp3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TimeServer {

    
        
        static final int PORT = 1337;
        
	public static void main(String[] args) {
		new TimeServer().run();
	}

	void run() { 
            EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new TimeServerHandler());

            b.bind(PORT).sync().channel().closeFuture().await();
        }   catch (InterruptedException ex) {
                Logger.getLogger(TimeServer.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            group.shutdownGracefully();
        }
	}

    static class TimeServerHandler extends
            SimpleChannelInboundHandler<DatagramPacket> {

		@Override
		protected void channelRead0(ChannelHandlerContext arg0,
				DatagramPacket arg1) throws Exception {
                    System.err.println(arg1);
                    if ("HEURE?".equals(arg1.content().toString(CharsetUtil.UTF_8))) {
                        arg0.write(new DatagramPacket(
                                Unpooled.copiedBuffer("HEURE: " + System.currentTimeMillis(), CharsetUtil.UTF_8), arg1.sender()));
                    }
			
		}

        }

    }

